<template>
  <div class="dialog-overlay" v-if="isVisible" >
    <div class="dialog-box">
      <header>
        <h3>{{ type === EDIT ? "修改收藏" : "添加收藏：" + title}}</h3>
        <div class="header-actions">
          <button class="close-btn" @click="closeModal">&times;</button>
        </div>
      </header>
      <div class="dialog-content">
        <!-- 评分类型 -->
        <div v-if="type === EDIT" class="radio-group">
            <input type="radio" name="type" value="我想看这部电影" v-model="radio" id="want">
            <label for="want">想看</label>
            <input type="radio" name="type" value="我看过这部电影" v-model="radio" id="seen">
            <label for="seen">看过</label>
        </div>
        <!-- 评分部分 -->
        <div class="rating-section" v-if="type === SEEN || radio === SEEN">
          <div class="rankstar" >
            <label>给个评价吧？(可选):</label>
            <div :class="['star-item', item.state]" v-for="(item, index) in starlist.list || []"
                 @mouseenter="changeScore(index)"
                 @click="fixedScore"

                 @mouseleave="resetScore">
            </div>

            <span class="review">{{ review }}</span>
            <div>
              <button class="toggle-btn" @click="toggleContent" :style="
             isCollapsed ?  'margin-left: 8.82vh;' :  'margin-left: 18.72vh;'
            ">
                {{ isCollapsed ? "高级(标签和短评) ▼" : "缩起 ▲" }}
              </button>
            </div>
          </div>
        </div>


        <div v-if="!isCollapsed">
          <!-- 标签输入 -->
          <div class="tags-section">
            <label>标签 (多个标签用空格分隔):</label>
            <input
                style="width: 98%;"
                type="text"
                v-model="tags"
                placeholder="输入标签"
            />
          </div>
          <div class="tags-content">
            <label>{{type === EDIT ? "我的标签" : "常用标签"}}：</label>
            <span v-for="genre in genres" class="tag-item" @click="addTags">{{ genre }}</span>
          </div>
          <!-- 简短评论 -->
          <div class="comment-section">
            <label>简短评论:</label>
            <textarea
                v-model="comment"
                maxlength="350"
                placeholder="写下您的感想"
            ></textarea>
            <span class="char-count">{{ comment.length }}/350</span>
          </div>
        </div>

        <!-- 底部按钮 -->
        <footer>
          <label>
            <input type="checkbox" checked disabled=""/>
            仅自己可见
          </label>
          <button class="save-btn" @click="saveData">保存</button>
        </footer>
      </div>
    </div>
  </div>
</template>



<script setup>
import {computed, defineProps, onMounted, reactive, ref, watch} from 'vue';
import {EDIT, SEEN} from '@/constant/constant'
import {useStore} from "vuex";
import {useRoute} from "vue-router";
import moment from "moment/moment";

const props = defineProps({
  isVisible: Boolean,
  title: String,
  type: String,
  genres: Array,
  ranks: Array,
  favouriteType: String
})

const emit = defineEmits(['close'])

const closeModal = () => {
  emit('close')
}

const store = useStore()
const route = useRoute()

// 标签
const tags = ref('')
// 是否收起
const isCollapsed = ref(false)
// 评论
const comment = ref('')
// 评分固定
const isFixed = ref(false)
// 单选框
const radio = ref(props.favouriteType)


const starlist = reactive({
  list: new Array(5).fill({state: 'normal'})
})

const id = route.query.id

watch(() => props.isVisible, (newVal) => {
  if (newVal) {
    const favouriteMovie = store.getters.getFavouriteMovieById(Number(id))
    if (props.type === EDIT && favouriteMovie) {
      starlist.list = favouriteMovie.rating.starlist
      radio.value = favouriteMovie.type
      tags.value = favouriteMovie.genres.join(' ')
      comment.value = favouriteMovie.abstract
    } else {
      starlist.list = new Array(5).fill({state: 'normal'})
      radio.value = ''
      tags.value = ''
      comment.value = ''
    }
  }
});


watch(() => props.ranks, (newVal) => {
  if (props.isVisible) {
      starlist.list = props.ranks
  }
});
// 固定评分
const fixedScore = () => {
  isFixed.value = true
}

// 改变评分
const changeScore = (index) => {
  let list = []
  let hasChanged = false

  starlist.list.forEach((item, _index) => {
    const newState = _index <= index ? 'full' : 'normal'
    if (item.state !== newState) {
      hasChanged = true
    }
    list.push({ ...item, state: newState })
  })

  if (hasChanged) {
    starlist.list = list
  }
}

// 评分
const review = computed(() => {
  const fullStars = starlist.list.filter(item => item.state === 'full').length
  switch (fullStars) {
    case 1:
      return '很差'
    case 2:
      return '较差'
    case 3:
      return '还行'
    case 4:
      return '推荐'
    case 5:
      return '力荐'
    default:
      return ''
  }
})

// 重置评分
const resetScore = () => {
  if (!isFixed.value) {
    if (props.type === EDIT ) {
      const favouriteMovie = store.getters.getFavouriteMovieById(Number(id))
      starlist.list = favouriteMovie.rating.starlist;
    } else {
      starlist.list = starlist.list.map(item => ({state: 'normal'}));
    }
  }
}

const addTags = (e) => {
  if (!tags.value.includes(e.target.innerText)) {
    tags.value += e.target.innerText + ' '
  }

}



const toggleContent = () => {
  isCollapsed.value = !isCollapsed.value;
}

const saveData = () => {
  store.commit('setFavouriteMovie', {
    rating: {
      starlist: starlist.list,
      review: review
    },
    title: props.type === EDIT ? radio.value : props.title,
    id: Number(id),
    type: props.type === EDIT ? radio.value : props.favouriteType,
    genres: tags.value.trim().split(' '),
    create_time: moment().format('YYYY-MM-DD HH:mm:ss'),
    abstract: comment.value || '无'
  })
   resetData()
}

const resetData = () => {
  starlist.list = new Array(5).fill({state: 'normal'})
  tags.value = ''
  comment.value = ''
  isCollapsed.value = false
  isFixed.value = false
  radio.value = ''
  closeModal()
}


</script>



<style scoped>
/* 覆盖整个页面的背景 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: transparent; /* 透明背景，移除灰黑效果 */
  display: flex;
  justify-content: center;
  align-items: center;
  pointer-events: none; /* 不阻止底层元素操作 */
  z-index: 1000;
}

/* 对话框样式 */
.dialog-box {
  background: #fff;
  width: 400px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2); /* 阴影效果 */
  overflow: hidden; /* 防止头部样式溢出 */
  pointer-events: auto; /* 仅对对话框本身启用交互 */
  border: 1px solid #ddd; /* 添加一个微弱的边框 */
}

/* 头部样式 */
header {
  background-color: #e5f3e1; /* 豆瓣绿色背景 */
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
}

header h3 {
  font-size: 16px;
  margin: 0;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.toggle-btn,
.close-btn {
  background: none;
  border: none;
  font-size: 14px;
  cursor: pointer;
  color: #bbbbbb;
}



.review {
  position: absolute;
  margin-left: 192px;
}

.toggle-btn {
  font: 12px Helvetica, Arial, sans-serif;
  line-height: 1.62;
  text-align: right;
  cursor: pointer;
  color: #37a;
  text-decoration: none;
}

.toggle-btn:hover {
  background-color: #37a;
  color: #FFFFFF;;
}

.close-btn:hover{
  color: #000;
}

/* 内容部分 */
.dialog-content {
  padding: 20px;
}

.radio-group {
  display: flex;
  gap: 10px;
}

.rating-section {
  margin-bottom: 20px;
}

.tags-section input {
  width: 100%;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
  margin-top: 8px;
}

.tags-content {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 20px
}

/* 标签样式 */
.tag-item {
  padding: 1px 3px;
  font-size: 12px;
  background-color: rgba(115, 143, 199, 0.25);
  color: #37a;;
  font-weight: bold;
  transition: background-color 0.3s ease, color 0.3s ease;
  cursor: pointer;
  text-align: center;
}

.tag-item:hover {
  background-color: #37a;
  color: #fff;
}

.comment-section {
  margin-top: 20px;
}

textarea {
  width: 100%;
  height: 60px;
  padding: 4px;
  border: 1px solid #ccc;
  border-radius: 4px;
  resize: none;
}

.char-count {
  font-size: 12px;
  color: #888;
  float: right;
}

footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
}

.save-btn,
.cancel-btn {
  background-color: #0077cc;
  color: #fff;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.save-btn:hover {
  background-color: #005fa3;
}


.rankstar {
  display: flex;
  align-items: center;
}

.score-star {
  margin-left: 10px;
  padding-top: 5px;

  .rankstar {
    transform: scale(1.3);
    transform-origin: 0 0;
  }
}

.star-item {
  width: 16px;
  height: 16px;
  background-size: cover;
  cursor: pointer;

  &.normal {
    background-image: url('/imgs/star.png');
  }

  &.full {
    background-image: url('/imgs/star-fill.png');
  }
}
</style>
